package com.example.zhou.zhihunews;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.zhou.adapter.NewsAdapter;

import com.example.zhou.base.BaseActivity;
import com.example.zhou.callback.OldNewsCallback;
import com.example.zhou.connect.LastestNewsConnect;
import com.example.zhou.callback.LatestNewsCallback;
import com.example.zhou.connect.OldNewsConnect;
import com.example.zhou.heplper.DetailTransition;
import com.example.zhou.model.LastestNews;
import com.example.zhou.model.StoriesBean;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class NewsActivity extends BaseActivity implements LatestNewsCallback,
        SwipeRefreshLayout.OnRefreshListener, OldNewsCallback, NewsAdapter.OnItemClick {
    private LastestNewsConnect lastestNewsConnect = new LastestNewsConnect();
    private LastestNews lastestNews = new LastestNews();
    private List<StoriesBean> storiesBeenlist = new ArrayList<>();
    private List<LastestNews.TopStoriesBean> topStoriesBeanList = new ArrayList<>();
    private List<String> list = new ArrayList<>();
    private List<Object> listObject = new ArrayList<>();
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private NewsAdapter adapter;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout refreshLayout;

    LinearLayoutManager layoutManager;
    private int lastVisibleItem;
    private int fistVisibleItem;

    private int page = 0;
    private boolean state = false;
    /*加载更多的foot*/
    private String foot = "";
    private OldNewsConnect oldNewsConnect = new OldNewsConnect();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        ButterKnife.bind(this);

        adapter = new NewsAdapter(this, listObject, list);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(layoutManager);
        refreshLayout.setOnRefreshListener(this);
        adapter.setOnItemClick(this);
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                lastestNewsConnect.getLatestNews(NewsActivity.this);

            }
        });

        recyclerView.addOnScrollListener(onScroll);

    }

    RecyclerView.OnScrollListener onScroll = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            fistVisibleItem = layoutManager.findFirstVisibleItemPosition();

        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            recyclerViewScrollState(newState);
        }
    };


    public void recyclerViewScrollState(int newState) {

        if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == recyclerView.getLayoutManager().getItemCount()) {

            if (refreshLayout.isRefreshing()) {

            }
        } else if (!state) {
            state = true;
            page++;
            preLoad();
        }


    }

    private void preLoad() {
        listObject.add(foot);
        adapter.notifyDataSetChanged();
        onLoadMore();
    }

    private void onLoadMore() {
        oldNewsConnect.getOldNews(getDate(page), this);
    }

    @Override
    public void onLastestNewsSuccess(String result) {


        Log.e("result", result);
        //     JSONObject jsonObject = new JSONObject();
        lastestNews = JSON.parseObject(result, LastestNews.class);
        this.topStoriesBeanList = lastestNews.getTop_stories();
        this.storiesBeenlist = lastestNews.getStories();
        final List<String> list = new ArrayList<>();

        for (int i = 0; i < topStoriesBeanList.size(); i++) {
            list.add("今日推荐");
        }
        this.list = list;

        listObject.addAll(topStoriesBeanList);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
                adapter.update(listObject, NewsActivity.this.list);
            }
        });

    }


    @Override
    public void onLastestNeswFail(String fail) {
        Looper.prepare();
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        listObject.clear();
        list.clear();
        lastestNewsConnect.getLatestNews(NewsActivity.this);
    }


    public String getDate(int i) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = calendar.getTime();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -i);
        //  Log.e("date", format.format(calendar.getTime()));
        String a = format.format(calendar.getTime());
        return a;
    }

    @Override
    public void onOldNewsSuccess(String result) {
        Log.e("result", result);
        refreshLayout.setRefreshing(false);
        listObject.remove(foot);

        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(result);
            JSONArray jsonArray = jsonObject.optJSONArray("stories");
            List<StoriesBean> listS = JSON.parseArray(jsonArray.toString(), StoriesBean.class);

            List<String> list1 = new ArrayList<>();
            for (int i = 0; i < topStoriesBeanList.size(); i++) {
                list1.add(getStringdate(getDate(page)));
            }

            listObject.addAll(listS);
            list.addAll(list1);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.update(listObject, list);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

        state = false;

    }

    private String getStringdate(String date) {
        return date.substring(0, 4) + "年" + date.substring(4, 6) + "月" + date.substring(6) + "日";
    }

    @Override
    public void onOldNewsFail(String fail) {
        Log.e("false", fail);
        state = false;
    }

    @Override
    public void OnClick(View view, Object o, int position) {
        Bundle bundle = new Bundle();
        ActivityOptionsCompat sceneTransitionAnimation;
        final Bundle transitionBundle;
        if (o instanceof StoriesBean) {
            bundle.putString("ID", ((StoriesBean) o).getId() + "");
            setTransitionName(view, o);

            final Pair pairs =
                    new Pair<>(view.findViewById(R.id.iv_title), NewsActivity.this.getString(R.string.transition));
            sceneTransitionAnimation = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(NewsActivity.this, pairs);

            //view.getRootView().findViewById(R.id.iv_title).setTransitionName(((LastestNews.TopStoriesBean) o).getId() + "");
            transitionBundle = sceneTransitionAnimation.toBundle();

        } else {
            bundle.putString("ID", ((LastestNews.TopStoriesBean) o).getId() + "");
            setTransitionName(view, o);
            final Pair pairs =
                    new Pair<>(view.findViewById(R.id.iv_title), NewsActivity.this.getString(R.string.transition));
            sceneTransitionAnimation = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(NewsActivity.this, pairs);

            //view.getRootView().findViewById(R.id.iv_title).setTransitionName(((LastestNews.TopStoriesBean) o).getId() + "");
            transitionBundle = sceneTransitionAnimation.toBundle();
        }


        Intent intent = new Intent(this, NewsInfoActivity.class);
        intent.putExtras(bundle);

        // Get the transition name from the string

        //Start the Intent
        ActivityCompat.startActivity(this, intent, transitionBundle);
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setTransitionName(View view, Object o) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

        } else {
            if (o instanceof LastestNews.TopStoriesBean)
                view.findViewById(R.id.iv_title).setTransitionName(((LastestNews.TopStoriesBean) o).getId() + "image");
            else if (o instanceof StoriesBean)
                view.findViewById(R.id.iv_title).setTransitionName(((StoriesBean) o).getId() + "image");

        }

    }

}
